package com.ruoyi.server;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.dto.MessageDTO;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//@ServerEndpoint("/ws/endpoint")这个是用？拼接的方式 配合 ↓
//        String queryString = session.getQueryString();
//        String[] params = queryString.split("=");//decodedToken.substring(7) 返回第七个字符后的数 ‘Bearer ’
@ServerEndpoint("/ws/endpoint/{token}")
@Component
public class WebSocketServer {
    private static final Map<Long, Session> userSessions = new ConcurrentHashMap<>();

    private static RedisCache redisCache;
    private static TokenService tokenService;
    // 提供公共的getter方法
    public static Map<Long, Session> getUserSessions() {
        return userSessions;
    }
    @Autowired
    public void setTokenService(TokenService tokenService,RedisCache redisCache) {
        WebSocketServer.redisCache = redisCache;
        WebSocketServer.tokenService = tokenService;
    }
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token){
        try {
            // 检查 Token 是否为空
            if (token == null || token.isEmpty()) {
                closeSessionWithError(session, CloseReason.CloseCodes.valueOf("10086"), "Token 不能为空");
                return;
            }

            // 解析 Token
            Map<String, Object> map = tokenService.parseToken(token);
            if (map == null || map.isEmpty()) {
                closeSessionWithError(session, CloseReason.CloseCodes.valueOf("10087") ,"Token 解析失败");
                return;
            }

            // 提取 Redis 键
            String strWithoutBraces = map.toString().replace("{", "").replace("}", "");
            String[] parts = strWithoutBraces.split("=");
            if (parts.length < 2) {
                closeSessionWithError(session, CloseReason.CloseCodes.valueOf("10088"), "Token 解析结果格式错误");
                return;
            }
            String redisKey = "login_tokens:" + parts[1];

            // 从 Redis 获取用户信息
            LoginUser user = redisCache.getCacheObject(redisKey);
            if (user == null) {
                closeSessionWithError(session, CloseReason.CloseCodes.valueOf("10089"), "未找到对应的用户信息");
                return;
            }

            // 绑定用户 ID 和会话
            Long userId = user.getUserId();
            session.getUserProperties().put("USER_ID", userId);
            userSessions.put(userId, session);
            System.out.println("用户 " + userId + " 连接成功");
        } catch (Exception e) {
            System.out.println("连接异常onOpen");
            // 处理未预料到的异常
            closeSessionWithError(session, CloseReason.CloseCodes.NO_STATUS_CODE, "服务器内部错误：" + e.getMessage());
            e.printStackTrace();
        }
    }
    // 关闭会话并发送错误信息的辅助方法
    private void closeSessionWithError(Session session, CloseReason.CloseCodes code, String reason) {
        try {
            session.close(new CloseReason(code, reason));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        String fromUserId = (String) session.getUserProperties().get("USER_ID");
        System.out.println("这"+fromUserId);
        System.out.println(message);
//        // 解析消息中的目标用户 ID
        MessageDTO msg = new ObjectMapper().readValue(message, MessageDTO.class);
        Session targetSession = userSessions.get(msg.getToUserId());
        if (targetSession != null && targetSession.isOpen()) {
//            targetSession.get|BasicRemote().sendText("来自于"+msg.getFromUserId()+ "发送给"+msg.getToUserId()+"消息是 " + msg.getContent());
            targetSession.getBasicRemote().sendText(message);
        }else{
            System.out.println("目标用户未在线或会话已关闭"+msg.getToUserId());
        }
    }
    // 群发消息给所有人（广播）
    private void broadcastMessage(String message) {
        userSessions.forEach((userId, session) -> {
            try {
                if (session.isOpen()) {
                    session.getBasicRemote().sendText(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        // 从会话属性中获取用户ID（更可靠的方式）
        Long userId = (Long) session.getUserProperties().get("USER_ID");

        if (userId != null) {
            // 移除前检查是否是同一个会话（防止并发问题）
            Session existingSession = userSessions.get(userId);
            if (existingSession != null && existingSession.getId().equals(session.getId())) {
                userSessions.remove(userId);
                System.out.println("用户 " + userId + " 连接关闭，原因: " + closeReason);
            }
        } else {
            System.out.println("检测到未认证连接关闭，会话ID: " + session.getId());
        }

        // 可选：清理其他关联资源
        try {
            if (session.isOpen()) {
                session.close();
            }
        } catch (IOException e) {
            System.err.println("关闭会话时发生异常: " + e.getMessage());
        }
    }
}